package com.smartpro.mis.modular.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.smartpro.mis.core.base.controller.BaseController;
import com.smartpro.mis.modular.business.neo4jEntity.ClickGroupBuyRelationship;
import com.smartpro.mis.modular.business.neo4jEntity.ClickLinkRelationship;
import com.smartpro.mis.modular.business.neo4jEntity.N4jProduct;
import com.smartpro.mis.modular.business.neo4jEntity.N4jUser;
import com.smartpro.mis.modular.business.service.IOrdersService;
import com.smartpro.mis.modular.business.service.IProductService;
import com.smartpro.mis.modular.business.service.IUserService;
import com.smartpro.mis.modular.system.dao.BuyNotPayRelationRepository;
import com.smartpro.mis.modular.system.dao.ClickGroupBuyRelationRepository;
import com.smartpro.mis.modular.system.dao.ClickLinkRelationRepository;
import com.smartpro.mis.modular.system.dao.GroupBuyRelationRepository;
import com.smartpro.mis.modular.system.model.*;
import com.smartpro.mis.rest.modular.auth.controller.dto.ResponseBean;
import com.smartpro.mis.rest.modular.auth.util.JwtTokenUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
//import com.smartpro.mis.core.log.LogObjectHolder;
import com.smartpro.mis.modular.business.service.IGroupBuyService;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 团购控制器
 *
 * @author Mengiy
 * @Date 2019-05-07 21:49:09
 */
@Controller
@RequestMapping("/api/service/groupBuy")
public class GroupBuyController extends BaseController {


    @Autowired
    private IGroupBuyService groupBuyService;
    @Autowired
    private IProductService productService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private ClickGroupBuyRelationRepository clickGroupBuyRelationRepository;
    @Autowired
    private ClickLinkRelationRepository clickLinkRelationRepository;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");





    /**
     * 获取团购列表
     */
//    @ApiOperation(value = "获取团购列表",notes = "查询全部团购")
    @RequestMapping(value = "/list")
    @ResponseBody
    @RequiresAuthentication
    public Object list(String condition) {
        return groupBuyService.selectList(null);
    }


    /**
     * 获取团购列表
     */
    @ApiOperation(value = "获取团购列表",notes = "查询全部团购")
    @RequestMapping(value = "/getGroupBuylist",method = RequestMethod.GET)
    @ResponseBody
    @RequiresAuthentication
    public Object getGroupBuylist() {
        return new ResponseBean(200,"operation success",groupBuyService.selectList(null));
    }


    /**
     * 多条件查询团购列表
     */
    @ApiOperation(value = "多条件查询团购列表",notes="多条件筛选团购列表" )
    @ApiImplicitParam(name = "params", value = "json格式查询条件", required = true, dataType = "Map")
    @RequestMapping(value = "/mulQuery",method = RequestMethod.POST)
    @ResponseBody
    @RequiresAuthentication
    public Object mulQuery(@RequestBody Map params) {
        JSONObject result = new JSONObject();
        return new ResponseBean(200,"operation success",groupBuyService.selectByMap(params));
    }


    /**
     * 查看商品的团购列表
     */
    @ApiOperation(value = "查看商品的团购列表",notes = "根据产品ID查看该产品的团购信息")
    @ApiImplicitParam(name="productID",value = "产品ID",required = true,dataType =  "Integer")
    @RequestMapping(value = "/listGroupBuyByProduct/{productID}",method = RequestMethod.GET)
    @ResponseBody
    @RequiresAuthentication
    public Object listGroupBuyByProduct(@PathVariable("productID") Integer productID) {
        Map condition = new HashMap();
        condition.put("productID",productID);
        List<GroupBuy> groupBuyList = groupBuyService.selectByMap(condition);
        List<JSONObject> groupBuys = new ArrayList<>();
        for(GroupBuy groupBuy: groupBuyList){
            JSONObject groupRecord = new JSONObject();
            JSONObject leaderJson = new JSONObject();
            leaderJson.put("leaderID",groupBuy.getLeaderID());
            User groupLeader = this.userService.selectById(groupBuy.getLeaderID());
            leaderJson.put("nickName",groupLeader.getNickName());
            leaderJson.put("headImage",groupLeader.getHeadImage());
            //现有数据模型找不到开团时间,设值为：团购创建时间
            groupRecord.put("groupLeader",groupLeader);
            groupRecord.put("groupStartTime",groupBuy.getCreateTime());

            groupRecord.put("numberOfMember",groupBuy.getNumberOfMember());

            List<JSONObject> memberList = new ArrayList<JSONObject>();
            String members = groupBuy.getMemberList();
            if(null!=members ){
                List<JSONObject> mList = JSONObject.parseArray(members,JSONObject.class);
                for(JSONObject groupMember : mList){
                    int uid = groupMember.getInteger("userID");
                    User u = userService.selectById(uid);
                    JSONObject obj = new JSONObject();
                    obj.put("memberID",uid);
                    obj.put("groupBuyTime",groupMember.getString("groupBuyTime"));
                    obj.put("nickName",u.getNickName());
                    obj.put("headImage",u.getHeadImage());
//               Map condition = new HashMap();
//               //此处逻辑不严谨，因为团购表跟订单表没有关联
//               condition.put("name",product.getName());
//               condition.put("userID",uid);
//               condition.put("isValid",0);
//               condition.put("groupPrice",groupBuy.getGroupPrice());
//               Orders order = (Orders) this.ordersService.selectByMap(condition).get(0);
//            obj.put("purchaseTime",order.getCreateTime());
                    obj.put("purchaseTime",groupBuy.getModifyTime());
                    memberList.add(obj);
                }
            }


            groupRecord.put("memberList",memberList);
            groupRecord.put("duration",groupBuy.getDuration());
            groupBuys.add(groupRecord);
        }
        return new ResponseBean(200,"operation success",groupBuys);

    }


    /**
     * 获取当前用户的拼团列表
     */
    @ApiOperation(value = "获取当前用户的拼团列表",notes="登录用户凭借token获取拼团列表" )
    @RequestMapping(value = "/getMyGroupBuy",method = RequestMethod.GET)
    @ResponseBody
    @RequiresAuthentication
    public Object getMyGroupBuy(HttpServletRequest request) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
        JwtTokenUtil jwt = new JwtTokenUtil();
        String username = jwt.getUsernameFromToken(authorization);
        Map<String,Object> condtion = new HashMap();
        condtion.put("wechat",username);
        User user = this.userService.selectByMap(condtion).get(0);
        int userID = user.getUserID();
//        Map condition = new HashMap();
//        condition.put("userID",userID);
        String matchStr = "\"userID\":"+userID;
//        System.out.println(matchStr);
        List<GroupBuy> groupBuyList = groupBuyService.getMyGroupBuyList(matchStr);
        List<JSONObject> groupBuys = new ArrayList<>();
        for(GroupBuy groupBuy: groupBuyList){
            JSONObject groupRecord = new JSONObject();
            JSONObject leaderJson = new JSONObject();
            leaderJson.put("leaderID",groupBuy.getLeaderID());
            User groupLeader = this.userService.selectById(groupBuy.getLeaderID());
            leaderJson.put("nickName",groupLeader.getNickName());
            leaderJson.put("headImage",groupLeader.getHeadImage());
            //现有数据模型找不到开团时间,设值为：团购创建时间
            groupRecord.put("groupLeader",groupLeader);
            groupRecord.put("groupStartTime",groupBuy.getCreateTime());
            groupRecord.put("productID", groupBuy.getProductID());


            List<JSONObject> memberList = new ArrayList<JSONObject>();
            String members = groupBuy.getMemberList();
            if(null!=members ) {
                List<JSONObject> mList = JSONObject.parseArray(members, JSONObject.class);
                for (JSONObject groupMember : mList) {
                    int uid = groupMember.getInteger("userID");
                    User u = userService.selectById(uid);
                    JSONObject obj = new JSONObject();
                    obj.put("memberID", uid);
                    obj.put("groupBuyTime", groupMember.getString("groupBuyTime"));
                    obj.put("nickName", u.getNickName());
                    obj.put("headImage", u.getHeadImage());
//               Map condition = new HashMap();
//               //此处逻辑不严谨，因为团购表跟订单表没有关联
//               condition.put("name",product.getName());
//               condition.put("userID",uid);
//               condition.put("isValid",0);
//               condition.put("groupPrice",groupBuy.getGroupPrice());
//               Orders order = (Orders) this.ordersService.selectByMap(condition).get(0);
//            obj.put("purchaseTime",order.getCreateTime());
                    obj.put("purchaseTime", groupBuy.getModifyTime());
                    memberList.add(obj);
                }
            }

            /**
             * 获取商品信息：购买数量、购买价格、商品名称、商品描述、商品小图片
             * 有团购肯定有订单记录
             */
            Product product = this.productService.selectById(groupBuy.getProductID());
            groupRecord.put("name",product.getName());
            groupRecord.put("description",product.getDescription());
            groupRecord.put("smallPicture",product.getSmallPicture());

            Map groupCondition = new HashMap();
            groupCondition.put("groupBuyID",groupBuy.getGroupBuyID());
            Orders orders = (Orders) this.ordersService.selectByMap(groupCondition).get(0);
            groupRecord.put("groupBuyNumber",orders.getNumberOfProduct());
            BigDecimal price = null;
            if(null!=orders.getInstantPrice()){
                price = orders.getInstantPrice();
            }else if(null!=orders.getLeaderPrice()){
                price = orders.getLeaderPrice();
            }else if(null!=orders.getGroupPrice()){
                price = orders.getGroupPrice();
            }
            groupRecord.put("memberList",memberList);
            groupRecord.put("buyPrice",price);
            groupRecord.put("duration",groupBuy.getDuration());
            groupBuys.add(groupRecord);
        }
        return new ResponseBean(200,"operation success",groupBuys);
    }



    /**
     * 新增团购
     */
    @ApiOperation(value = "新增团购",notes = "根据团购ID添加团购信息记录")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ApiImplicitParam(name="groupBuy",value = "团购信息",required = true,dataType =  "GroupBuy")
    @ResponseBody
    @RequiresAuthentication
    public Object add(@RequestBody GroupBuy groupBuy) {
        groupBuyService.insert(groupBuy);
        return new ResponseBean(200,"operation success",groupBuy);
    }

    /**
     * 删除团购
     */
    @ApiOperation(value = "删除团购",notes = "根据团购ID删除团购信息")
    @RequestMapping(value = "/delete/{groupBuyId}",method = RequestMethod.GET)
    @ApiImplicitParam(name="groupBuyId",value = "团购ID",required = true,dataType =  "Integer")
    @ResponseBody
    @RequiresAuthentication
    public Object delete(@PathVariable("groupBuyId") Integer groupBuyId) {
        groupBuyService.deleteById(groupBuyId);
        return new ResponseBean(200,"operation success",null);
    }

    /**
     * 修改团购
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ApiImplicitParam(name="groupBuy",value = "团购信息",required = true,dataType =  "GroupBuy")
    @ResponseBody
    @RequiresAuthentication
    public Object update(@RequestBody GroupBuy groupBuy) {
        groupBuyService.updateById(groupBuy);
        return new ResponseBean(200,"operation success",null);
    }

    /**
     * 团购详情
     */
    @ApiOperation(value = "团购详情查看",notes = "根据团购ID查看该团购的信息")
    @RequestMapping(value = "/detail/{groupBuyId}",method = RequestMethod.GET)
    @ApiImplicitParam(name="groupBuyId",value = "团购ID",required = true,dataType =  "Integer")
    @ResponseBody
    @RequiresAuthentication
    public Object detail(@PathVariable("groupBuyId") Integer groupBuyId) {
        return new ResponseBean(200,"operation success",groupBuyService.selectById(groupBuyId));
    }


    @ApiOperation(value = "用户点击团购链接",notes = "一方面建立neo4j关系，一方面查看团购详情")
    @ApiImplicitParam(name="jsonObject",value = "json格式，包含元素：leaderID,groupBuyID",dataType = "JSONObject")
    @RequestMapping(value = "/clickLink",method = RequestMethod.POST)
    @ResponseBody
    @RequiresAuthentication
    public Object clickGroupLink(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int leaderID = jsonObject.getInteger("leaderID");
        int groupBuyID = jsonObject.getInteger("groupBuyID");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
        JwtTokenUtil jwt = new JwtTokenUtil();
        String username = jwt.getUsernameFromToken(authorization);
        Map<String,Object> condtion = new HashMap();
        condtion.put("wechat",username);
        User user = this.userService.selectByMap(condtion).get(0);

        JSONObject res = new JSONObject();
        GroupBuy groupBuy = this.groupBuyService.selectById(groupBuyID);

        /**
         * 1. 建立用户与团长的点击团购商品关系
         * 2. 建立用户与商品的点击关系
         */
        ClickGroupBuyRelationship clickGroupBuyRelationship = new ClickGroupBuyRelationship(sdf.format(new Date()),new N4jUser(leaderID),new N4jUser(user.getUserID()));
        this.clickGroupBuyRelationRepository.save(clickGroupBuyRelationship);

        ClickLinkRelationship clickLinkRelationship = new ClickLinkRelationship(sdf.format(new Date()),new N4jUser(user.getUserID()),new N4jProduct(groupBuy.getProductID()));
        this.clickLinkRelationRepository.save(clickLinkRelationship);

        Product product = this.productService.selectById(groupBuy.getProductID());
        res.put("name",product.getName());
        res.put("description",product.getDescription());
        res.put("bigPicture",product.getBigPicture());
        res.put("OriginalPrice",groupBuy.getOriginPrice());

        //如果是团长购买，此处显示的是团长价格
        if(user.getUserID() == leaderID){
            res.put("groupPrice",groupBuy.getLeaderPrice());
        }else {
            res.put("groupPrice",groupBuy.getGroupPrice());
        }
        res.put("createTime",groupBuy.getCreateTime());
        res.put("duration",groupBuy.getDuration());

        JSONObject groupRecord = new JSONObject();
        groupRecord.put("leaderID",leaderID);
        User groupLeader = this.userService.selectById(leaderID);
        groupRecord.put("nickName",groupLeader.getNickName());
        groupRecord.put("headImage",groupLeader.getHeadImage());
        //现有数据模型找不到开团时间,设值为：团购创建时间
       groupRecord.put("groupStartTime",groupBuy.getCreateTime());

       List<JSONObject> memberList = new ArrayList<JSONObject>();
       String members = groupBuy.getMemberList();
        if(null!=members ){
            List<JSONObject> mList = JSONObject.parseArray(members,JSONObject.class);
            for(JSONObject groupMember : mList){
                int uid = groupMember.getInteger("userID");
                User u = userService.selectById(uid);
                JSONObject obj = new JSONObject();
                obj.put("memberID",uid);
                obj.put("groupBuyTime",groupMember.getString("groupBuyTime"));
                obj.put("nickName",u.getNickName());
                obj.put("headImage",u.getHeadImage());
//               Map condition = new HashMap();
//               //此处逻辑不严谨，因为团购表跟订单表没有关联
//               condition.put("name",product.getName());
//               condition.put("userID",uid);
//               condition.put("isValid",0);
//               condition.put("groupPrice",groupBuy.getGroupPrice());
//               Orders order = (Orders) this.ordersService.selectByMap(condition).get(0);
//            obj.put("purchaseTime",order.getCreateTime());
                obj.put("purchaseTime",groupBuy.getModifyTime());
                memberList.add(obj);
            }
        }
      groupRecord.put("memberList",memberList);
      res.put("groupRecord",groupRecord);
      return  new ResponseBean(200,"operation success",res);
    }
}
